package com.dacool.fragment;

import static com.dacool.util.ViewUtils.findViewById;
import static com.dacool.util.ViewUtils.rp;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.dacool.app.sale.R;
import com.dacool.helper.DaCoolHelper;
import com.dacool.http.BaseRequest;
import com.dacool.http.BaseRequest.ResponseHandler;
import com.dacool.http.GetProductInfoRequest;
import com.dacool.model.CartItem;
import com.dacool.model.DacoolProduct;
import com.dacool.model.DacoolProduct.ProductSpec;
import com.dacool.util.ViewUtils;
import com.dacool.view.CirclePageIndicator;
import com.dacool.view.MyImageViewPager;

public class ProductInfoFragment extends BaseFragment implements
		OnClickListener {

	private int amount = 1;
	private DacoolProduct product;
	private TextView titleLabel;
	private LinearLayout specCellContainer;
	private TextView descriptionLabel;
	private TextView priceLabel;
	private ImageButton removeBtn;
	private ImageButton addBtn;
	private EditText amountEdit;
	private Button buttonBuy;
	private MyImageViewPager mViewPager;
	private CirclePageIndicator mPageIndicator;

	private int specIndex = -1;

	private ArrayList<Button> specButtons = new ArrayList<Button>();

	@Override
	protected int myLayoutID() {
		// TODO Auto-generated method stub
		return R.layout.product_info;
	}

	@Override
	protected View myView() {
		// TODO Auto-generated method stub
		return null;
	}

	public void setProduct(DacoolProduct product) {
		this.product = product;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewCreated(view, savedInstanceState);
		titleLabel = findViewById(view, R.id.titleLabel);
		specCellContainer = findViewById(view, R.id.specContainer);
		descriptionLabel = findViewById(view, R.id.description);
		priceLabel = findViewById(view, R.id.priceLabel);
		removeBtn = findViewById(view, R.id.buttonRemove);
		amountEdit = findViewById(view, R.id.amountInput);
		addBtn = findViewById(view, R.id.buttonAdd);
		buttonBuy = findViewById(view, R.id.buttonBuy);
		mViewPager = findViewById(view, R.id.productImages);
		mPageIndicator = findViewById(view, R.id.pageIndicator);
		if (product == null)
			return;
		titleLabel.setText(product.getName());
		descriptionLabel.setText(product.getDescription());
		amountEdit.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				if(event.getAction()==KeyEvent.ACTION_UP){
					try{
						amount = Integer.parseInt(amountEdit.getText().toString());
					}catch(Exception e){
					}
					amountEdit.setText(amount+"");
				}
				return false;
			}
		});
		amountEdit.setText("" + amount);
		priceLabel.setText(String.format("%.2f", product.getPrice()));
		removeBtn.setOnClickListener(this);
		addBtn.setOnClickListener(this);
		buttonBuy.setOnClickListener(this);

		mPageIndicator.setFillColor(0xff85c400);
		mPageIndicator.setPageColor(0xff888888);
		mPageIndicator.setStrokeWidth(0);
		mPageIndicator.setRadius(rp(5));
		mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int pos) {
				// TODO Auto-generated method stub
				int realPos = ((pos - 500) % mViewPager.getRealCount() + mViewPager
						.getRealCount()) % mViewPager.getRealCount();
				mPageIndicator.setCurrentItem(realPos);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub

			}
		});

	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		loadProductInfo();
	}

	private void loadProductInfo() {
		new GetProductInfoRequest().setId(product.getId())
				.setHandler(new ResponseHandler() {

					@Override
					public void handleResponse(BaseRequest request,
							int statusCode, String errorMsg, String response) {
						if (statusCode != 200)
							return;
						JSONObject json;
						try {
							json = new JSONObject(response);
							JSONObject obj = json.getJSONObject("data");
							DacoolProduct aproduct = new DacoolProduct();
							aproduct.setName(obj.getString("name"));
							aproduct.setDescription(obj.getString("intro"));
							// XXX price should be double already!!!
							aproduct.setPrice(obj.getDouble("price"));
							aproduct.setId(obj.getString("goodsId"));
							JSONArray arr = obj.optJSONArray("bigPics");
							ArrayList<String> urls = new ArrayList<String>();
							if(arr!=null){
								for(int i = 0;i<arr.length();i++)
									urls.add(arr.getString(i));
							}
							if(urls.size()==0){
								urls.add(obj.getString("thumbnailPic"));
							}
							aproduct.setImageUrls(urls);
							product = aproduct;
							ProductInfoFragment.this.updateInfo();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				}).start();
	}

	private void updateInfo() {

		ViewUtils.runInMainThread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub

				titleLabel.setText(product.getName());
				descriptionLabel.setText(product.getDescription());
				amountEdit.setText("" + amount);
				priceLabel.setText(String.format("%.2f", product.getPrice()));
				mViewPager.setImageUrls(product.getImageUrls());
				mViewPager.setAutoScroller(false);
				mPageIndicator.setCount(product.getImageUrls().size());
				specCellContainer.removeAllViews();
				specButtons.clear();
				if (product.getProductSpecs() != null)

					for (ProductSpec spec : product.getProductSpecs()) {
						Button button = new Button(getActivity());
						button.setTextSize(rp(8));
						button.setText(spec.name);
						button.setBackgroundResource(R.color.buttoncolor);
						button.setTextColor(Color.BLACK);
						button.setOnClickListener(ProductInfoFragment.this);
						button.setTag(spec.id);
						button.setPadding(0, 0, 0, 0);
						LayoutParams lp = new LayoutParams(
								LayoutParams.WRAP_CONTENT,
								LayoutParams.MATCH_PARENT);
						lp.setMargins(rp(5), 0, 0, 0);
						lp.gravity = Gravity.CENTER_VERTICAL;
						button.setGravity(Gravity.CENTER);
						specCellContainer.addView(button, lp);
						specButtons.add(button);
					}
				if (specButtons.size() > 0) {
					specIndex = 0;
					specButtons.get(0).setBackgroundColor(0xFF85C400);
					specButtons.get(0).setTextColor(Color.WHITE);
					// btn.setSelected(true);
					// btn.setClickable(true);
				}
			}
		});

	}

	@Override
	public void onClick(View v) {
		if (v == addBtn) {
			amount++;
			amountEdit.setText("" + amount);
		} else if (v == removeBtn) {
			if (amount > 1) {
				amount--;
			}
			amountEdit.setText("" + amount);
		} else if (v == buttonBuy) {
			CartItem item = new CartItem();
			item.setAmount(amount);
			item.setProduct(product);
//			Log.d("test", "buy product:" + product);
			DaCoolHelper.sharedInstance().addItem(item, amount);
			Toast.makeText(getActivity(), "加入购物车", Toast.LENGTH_SHORT).show();
		} else {
			for (int i = 0; i < specButtons.size(); i++) {
				Button btn = specButtons.get(i);
				if (btn == v) {
					specIndex = i;
					btn.setBackgroundColor(0xFF85C400);
					btn.setTextColor(Color.WHITE);
					// btn.setSelected(true);
					// btn.setClickable(true);
				} else {
					btn.setBackgroundColor(Color.WHITE);
					btn.setTextColor(Color.BLACK);
					// btn.setSelected(false);
					// btn.setEnabled(true);
				}
			}
		}
		super.onClick(v);
	}

	// @Override
	// protected boolean showDefaultLeftButton() {
	// return true;
	// }

	@Override
	protected boolean showDefaultSecondLeftButton() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public String titleText() {
		// TODO Auto-generated method stub
		return "商品详情";
	}
}
